package org.rich.charlesmurphy.core.parser;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;

import org.ddevil.data.Data;
import org.ddevil.data.set.BasicDataSet;
import org.ddevil.data.set.DataSet;
import org.rich.charlesmurphy.core.ParseResult;
import org.rich.charlesmurphy.core.Parser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.Ostermiller.util.CSVParser;

/**
 * Parser for a CSV file.
 * @author Rich O'Connell
 */
public class CsvParser implements Parser {

	private Logger log = LoggerFactory.getLogger(getClass());

	private String[] ids;

	public CsvParser(String[] ids) {
		this.ids = ids;
	}

	/**
	 * @param ids the ids to set
	 */
	public void setIds(String[] ids) {
		this.ids = ids;
	}

	/**
	 * {@inheritDoc}
	 */
	public ParseResult parse(File csv) {

		Reader r = null;
		String[][] res = null;
		try {
			try {

				r = new BufferedReader(new FileReader(csv));
				res = CSVParser.parse(r);
				log.info("Parsed [{}] records from file: [{}]", res != null ? res.length : 0, csv);

			}
			finally {
				if (r != null) {
					r.close();
				}
			}
		}
		catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		if (res != null && res.length > 0) {

			String[] labels = res[0];
			DataSet<Data> ds = new BasicDataSet(res, ids, 1);

			return new ParseResult(ds, labels);

		}
		return null;
	}

}
